package net.dataslim.invoke;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

import net.dataslim.annotations.DataSlimClass;

public class DataSlimInput {
	
	public Object unProxied(Object input) throws Exception{
		if (input instanceof Collection){
			input = unProxiedCollection((Collection)input);
		}else if(input instanceof Map){
				//Nao implementado ainda
		}else{
			input = unProxiedObject(input);
		}
		return input;
	}
	
	protected Object unProxiedObject(Object input){
		try{
			if (input.getClass().isAnnotationPresent( DataSlimClass.class )){
				Method munproxied = input.getClass().getMethod("getUnDataSlim", new Class[]{});
				input = munproxied.invoke( input, new Object[]{} );
			}
		}catch(Exception e){
			//Nao precisa gerar excecao
		}
		return input;
	}
	
	@SuppressWarnings("unchecked")
	protected Collection unProxiedCollection(Collection inputCollection) throws Exception{
	    Collection inputCollectionUnProxied = inputCollection;
		if (!inputCollection.isEmpty()){			
			Iterator it = inputCollection.iterator();
			if (it.hasNext()){
				Object data = it.next();
				if (data.getClass().isAnnotationPresent(DataSlimClass.class)){
					inputCollectionUnProxied = new ArrayList();
					do{
						inputCollectionUnProxied.add(unProxied(data));
						data = it.next();
					}while(it.hasNext());
				}
			}
			
		}
		return inputCollectionUnProxied;
	}
}
